const express = require('express');
const router = express.Router();
const db = require('../../../db/index');
const path = require('path');
const multer = require('multer');
const fs = require('fs');

// 文件图片上传的参数
const storage = multer.diskStorage({
  destination: path.join(__dirname, '../../../static/admin/uploads'),
  filename: function (req, file, cb) {
    var type = file.originalname.split('.')[1];
    cb(null, `${file.fieldname}-${Date.now().toString()}.${type}`);
  },
});

//文件限制
const limits = {
  fields: 10, //非文件字段的数量
  fileSize: 1000 * 1024, // 文件大小   单位  b
  files: 5,
};

// 文件图片上传的实例
const upload = multer({ storage: storage, limits: limits });

// 缩略图上传
router.post('/upload', upload.single('file'), (req, res) => {
  res.send({
    code: 0,
    url: '/admin/uploads/' + req.file.filename,
  });
});

// 是否展示is_show （没问题）
router.get('/show', (req, res) => {
  const id = req.query.id;
  const show = req.query.show ? req.query.show : '';
  let sql = '';
  if (show) {
    // 修改数据库
    sql = `update news set is_show=${show} where news_id=${id}`;
  }
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.affectedRows == 1) {
      return res.send({
        code: 1,
        msg: '修改成功',
      });
    } else {
      return res.send({
        code: 0,
        msg: '修改失败',
      });
    }
  });
});

// 渲染新闻导航页面  （没问题）

router.get('/list', (req, res) => {
  const sql = `select * from new_care where is_delete=1`;
  db.query(sql, (err, results) => {
    if (err) {
      throw err.message;
    }
    // console.log(results);
    res.render('admin/newslist', { category: results });
  });
});

// 渲染新闻表格内容 （没问题）
router.get('/query', (req, res) => {
  // const sql = `select * from news order by news_id desc`;
  const sql = `select news_id,news_name,news_title,news_content,news_date,news_pic,is_show,new_name from news,new_care where news.new_id=new_care.new_id`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({
        code: 1,
        mag: err.message,
      });
    }
    if (results.length != 0) {
      return res.send({
        code: 0,
        msg: '数据渲染表格成功',
        data: results,
        count: 100,
      });
    } else {
      return res.send({
        code: 1,
        msg: '渲染失败',
      });
    }
  });
});

// 增加上传新闻的路由  （没问题）
router.post('/insert', (req, res) => {
  const { news_name, news_title, news_date, news_content, news_pic, news_img, new_id } = req.body;

  // 判断重复
  const sql = `select * from news where news_name='${news_name}'`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({
        code: 0,
        msg: err.message,
      });
    }
    if (results.length != 0) {
      return res.send({
        code: 0,
        msg: '用户名重复',
      });
    }
    // 添加
    const strsql = `insert into news(news_name,news_title,news_date,news_content,news_pic,news_img,new_id) values(?,?,?,?,?,?,?)`;
    db.query(
      strsql,
      [news_name, news_title, news_date, news_content, news_pic, news_img, new_id],
      (err, results) => {
        // console.log()
        if (err) {
          return res.send({ code: 0, msg: err.message });
        }
        if (results.affectedRows == 1) {
          return res.send({ code: 1, msg: '添加成功' });
        } else {
          return res.send({
            code: 0,
            msg: '添加失败',
          });
        }
      }
    );
  });
});

// 删除一条新闻  (没问题)  软删除
router.get('/delete', (req, res) => {
  // const {news_id} = req.query.id;
  // console.log(req.query)
  const sql = `delete from news where news_id=${req.query.id}`;

  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: `删除失败${err.message}` });
    }
    if (results.affectedRows == 1) {
      // const url = path.join(__dirname, '../../../static',news_pic);
      // fs.unlink([url], error => {
      //   if (error) {
      //     return res.send({ code: 0, msg: error.message });

      //   }
      // });
      return res.send({
        code: 1,
        msg: '删除成功',
      });
    } else {
      return res.send({
        code: 0,
        msg: '删除失败',
      });
    }
  });
});

// 修改新闻内容  把内容渲染进表格   (没问题)

router.get('/upluad', (req, res) => {
  // console.log(req.query);
  // const sql = `select * from news where news_id=${req.query.id}`
  const sql = `select new_list,news_id,news_name,news_title,news_date,news_content,news_pic,news_img,is_show,new_name from news,new_care where news_id=${req.query.id} and news.new_id=new_care.new_id`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.length == 1) {
      return res.send({
        code: 1,
        msg: '渲染成功',
        data: results[0],
      });
    } else {
      return res.send({
        code: 0,
        msg: '渲染失败',
      });
    }
  });
});

// 修改后表单上传  （没问题）
router.post('/update', (req, res) => {
  // 不变的图片

  // console.log(req.body);
  const {
    news_id,
    news_content,
    news_date,
    new_news_img,
    old_news_img,
    news_name,
    news_title,
    oldnews_pic,
    news_pic,
    new_id,
  } = req.body;

  const sql =
    'update news set news_name=?,news_title=?,news_content=?,news_date=?,news_pic=?,news_img=?,new_id=? where news_id=?';
  db.query(
    sql,
    [news_name, news_title, news_content, news_date, news_pic, new_news_img, new_id, news_id],
    (err, results) => {
      if (err) {
        return res.send({ code: 0, msg: err.message });
      }
      if (results.affectedRows == 1) {
        if (new_news_img != old_news_img) {
          const img_url = path.join(__dirname, '../../../static', old_news_img);
          fs.unlink(img_url, err => {
            if (err) {
              return res.send({ code: 0, msg: '失败' });
            }
          });
        }
        if (oldnews_pic != news_pic) {
          const img_url = path.join(__dirname, '../../static', oldnews_pic);
          fs.unlink(img_url, err => {
            if (err) {
              return res.send({ code: 0, msg: '失败' });
            }
          });
        }
        return res.send({ code: 1, msg: '修改成功' });
      } else {
        return res.send({ code: 1, msg: '修改失败' });
      }
    }
  );
});
// 查看页面 （没问题）
router.get('/listf', (req, res) => {
  const sql = `select news.*,new_name from news,new_care where news_id=${req.query.id} and news.new_id=new_care.new_id`;
  db.query(sql, (err, results) => {
    if (err) {
      throw err.message;
    }
    if (results.length == 1) {
      res.render('admin/newsLook', { data: results[0] });
    }
  });
});
module.exports = router;
